package org.yray.sip.base;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;


import java.net.InetSocketAddress;

@Slf4j
public abstract class AbstractSender implements SenderHandler {
    protected SipMsg sipMsg;
    protected Channel channel;
    protected SipServerTable sipServerTable;



    @Override
    public void send() {
        String msg=getSendMsg();
        InetSocketAddress sender=getAutoISA();
        if(sender==null)
        {
            log.error("sender is null msg={}",sipMsg);
            return;
        }
        ByteBuf byteBuf = Unpooled.copiedBuffer(msg.getBytes());
        channel.writeAndFlush(new DatagramPacket(byteBuf, sender));
        //log.info("send to {},{} -----------------------------------------",sender.getAddress().getHostAddress(),sender.getPort());
        log.info("sipMsg={}",msg);
    }

    @Override
    public String getSendMsg()
    {
       return sipMsg.toString();
    }

    protected InetSocketAddress getServerISA()
    {
       return sipServerTable.getServerISA();
    }

    protected InetSocketAddress getAutoISA()
    {
        InetSocketAddress serverISA=sipServerTable.getServerISA();
        //因为这是代理，服务器发的就转给客户端，客户端发的就转给服务器
        if(sipMsg.getReceiveIp().equals(serverISA.getAddress().getHostAddress()))
        {
            return getViaISA();
        }
        return serverISA;
    }

    protected  String getClientIpPort()
    {
        return sipMsg.getClientIpPort();
    }


    protected InetSocketAddress getViaISA()
    {
        String msgLine=sipMsg.getMsgLine(MsgEle.VIA);
        String ipPort=RegexUtils.findIpPort(msgLine);
        if(StringUtils.isEmpty(ipPort))
        {
            log.error("ipPort is null ={},try getClientIpPort",msgLine);
            ipPort=getClientIpPort();
        }
        return sipServerTable.getUserISA(ipPort.split(MsgEle.ELE_SEPARATOR)[0],Integer.valueOf(ipPort.split(MsgEle.ELE_SEPARATOR)[1]));
    }
}
